package com.lanchetech.admin.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.admin.service.BargainService;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BargainEditResp;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.BargainDetailVO;
import com.lanchetech.bean.vo.BargainEditVO;
import com.lanchetech.bean.vo.BargainRecordVO;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.common.enums.ToggleEnum;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BargainServiceImpl implements BargainService {

    @Autowired
    BargainActivityMapper bargainActivityMapper;
    
    @Autowired
    BargainSpuMapper bargainSpuMapper;
    
    @Autowired
    BargainSkuMapper bargainSkuMapper;

    @Autowired
    BargainRecordMapper bargainRecordMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    BargainDetailMapper bargainDetailMapper;
    
    @Override
    public ResultData<BasePageResp<BargainActivity>> getBargainPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<BargainActivity> list = bargainActivityMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BargainEditResp> getBargainDetail(Long id) {
        BargainEditResp resp = new BargainEditResp();
        resp.setActivity(bargainActivityMapper.selectByPrimaryKey(id));
        resp.setSpuList(bargainSpuMapper.findAllByActivityId(id));
        resp.setSkuList(bargainSkuMapper.findAllByActivityId(id));
        return new ResultData<>(resp);
    }

    @Override
    public BaseResp editBargain(BargainEditVO req) {
        BargainActivity activity = req.getActivity();
        List<BargainSpu> spuList = req.getSpuList();
        List<BargainSku> skuList = req.getSkuList();
        long[] deleteList = req.getDeleteList();

        if (activity.getId() == null) {
            // 创建
            activity.setCreatedAt(new Date());
            activity.setUpdatedAt(new Date());
            activity.setDeleted(DeletedEnum.DEFAULT.getStatus());
            bargainActivityMapper.insert(activity);

            for (BargainSpu bargainSpu : spuList) {
                bargainSpu.setActivityId(activity.getId());
                bargainSpu.setCreatedAt(new Date());
                bargainSpu.setUpdatedAt(new Date());
            }
            bargainSpuMapper.batchInsert(spuList);

            for (BargainSku item : skuList) {
                item.setSales(0);
                item.setActivityId(activity.getId());
                item.setCreatedAt(new Date());
                item.setUpdatedAt(new Date());
            }
            bargainSkuMapper.batchInsert(skuList);
        } else {
            // 编辑
            activity.setUpdatedAt(new Date());
            bargainActivityMapper.updateByPrimaryKeySelective(activity);

            // spu
            List<BargainSpu> newSpuList = new ArrayList<>();
            List<BargainSpu> updateSpuList = new ArrayList<>();
            for (BargainSpu bargainSpu : spuList) {
                if (bargainSpu.getId() == null) {
                    bargainSpu.setActivityId(activity.getId());
                    bargainSpu.setCreatedAt(new Date());
                    bargainSpu.setUpdatedAt(new Date());
                    newSpuList.add(bargainSpu);
                } else {
                    bargainSpu.setUpdatedAt(new Date());
                    updateSpuList.add(bargainSpu);
                }
            }
            if (newSpuList.size() > 0) {
                bargainSpuMapper.batchInsert(newSpuList);
            }
            if (updateSpuList.size() > 0) {
                bargainSpuMapper.updateBatchSelective(updateSpuList);
            }

            //sku
            List<BargainSku> newSkuList = new ArrayList<>();
            List<BargainSku> updateSkuList = new ArrayList<>();
            for (BargainSku bargainSku : skuList) {
                if (bargainSku.getId() == null) {
                    bargainSku.setSales(0);
                    bargainSku.setActivityId(activity.getId());
                    bargainSku.setCreatedAt(new Date());
                    bargainSku.setUpdatedAt(new Date());
                    newSkuList.add(bargainSku);
                } else {
                    bargainSku.setUpdatedAt(new Date());
                    updateSkuList.add(bargainSku);
                }
            }
            if (newSkuList.size() > 0) {
                bargainSkuMapper.batchInsert(newSkuList);
            }
            if (updateSkuList.size() > 0) {
                bargainSkuMapper.updateBatchSelective(updateSkuList);
            }

            if (!ArrayUtils.isEmpty(deleteList)) {
                bargainSpuMapper.deleteByActivityIdAndSpuIds(activity.getId(), deleteList);
                bargainSkuMapper.deleteByActivityIdAndSpuIds(activity.getId(), deleteList);
            }
        }
        return new BaseResp();
    }

    @Override
    public ResultData<BasePageResp<BargainRecordVO>> getBargainRecordPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<BargainRecordVO> list = bargainRecordMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, Spu> spuMap = daoService.getSpuMap(list.stream().map(BargainRecordVO::getSpuId).collect(Collectors.toList()));
            Map<Long, Sku> skuMap = daoService.getSkuMap(list.stream().map(BargainRecordVO::getSkuId).collect(Collectors.toList()));
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(BargainRecordVO::getUserId).collect(Collectors.toList()));

            List<BargainActivity> activityList = bargainActivityMapper.findAllByIds(list.stream().map(BargainRecordVO::getActivityId).collect(Collectors.toList()));

            Map<Long, BargainActivity> activityMap = new HashMap<>();
            activityList.stream().forEach(item->activityMap.put(item.getId(), item));

            list.stream().forEach(item -> {
                item.setMainImage(spuMap.get(item.getSpuId()).getMainImage());
                item.setSpuName(spuMap.get(item.getSpuId()).getName());
                item.setSkuPrice(skuMap.get(item.getSkuId()).getPrice());
                item.setSpecValues(skuMap.get(item.getSkuId()).getSpecValues());
                item.setNickname(userMap.get(item.getUserId()).getNickname());
                item.setAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setActivityName(activityMap.get(item.getActivityId()).getName());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<BargainDetailVO>> getBargainDetailPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<BargainDetailVO> list = bargainDetailMapper.findAllPage(req);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, User> userMap = daoService.getUserMap(list.stream().map(BargainDetailVO::getUserId).collect(Collectors.toList()));

            list.stream().forEach(item -> {
                item.setAvatar(userMap.get(item.getUserId()).getAvatar());
                item.setNickname(userMap.get(item.getUserId()).getNickname());
            });
        }
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp deleteBargain(Long id) {
        bargainActivityMapper.updateDeletedAndStatusById(DeletedEnum.DELETED.getStatus(), ToggleEnum.OFF.getStatus(),id);
        bargainSpuMapper.updateDeletedAndStatusByActivityId(DeletedEnum.DELETED.getStatus(), ToggleEnum.OFF.getStatus(),id);
        return new BaseResp();
    }
}